/*
Copyright (c) 2009, Young Digital Planet SA
All rights reserved.

* Redistribution and use in source and binary forms, with or without 
  modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this 
  list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, 
  this list of conditions and the following disclaimer in the documentation 
  and/or other materials provided with the distribution.
* Neither the name of the Young Digital Planet SA nor the names of its 
  contributors may be used to endorse or promote products derived from this 
  software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
package pl.ydp.utils
{
	/**
	 * Narzędzia do operowania na tekstach
	 */
	public class TextUtil
	{
		/**
		 * Typy języków do konwersji cyfr
		 */
		public static const LANGUAGE_TYPE_ARABIC:String = "arabic";
		
		/**
		 * Tablice z kodami UTF8 dla cyfr 0-9 w poszczególnych jezykach
		 */
		public static const DIGITS_TYPE_ARABIC:Array = new Array("\u0660", "\u0661", "\u0662", "\u0663", "\u0664", "\u0665", "\u0666", "\u0667", "\u0668", "\u0669" );
		
		private static var WIDTH_BASE:Object = { };
		
		/**
		 * Waga dla liter podobnych do i
		 */
		public static const iWidth:uint = 3;
		/**
		 * Waga dla liter podobnych do f,t
		 */
		public static const fWidth:uint = 4;
		/**
		 * Waga dla liter podobnych do m
		 */
		public static const mWidth:uint = 6;
		/**
		 * Szerokośc pozostałych znaków
		 */
		public static const charWidth:uint = 5;
		/**
		 * Znaki podobne do i
		 */
		public static const iChars:Array = 
			["i", "l", "j" ];
		/**
		 * Znaki podobne do f
		 */
		public static const fChars:Array = 
			["f", "t", "r", " " ];
		/**
		 * Znaki podobne do m
		 */
		public static const mChars:Array = 
			["m","w"];
		
		/**
		 * Konwertuje cyfry w wejściowym ciągu na znaki reprezentujące te same cyfry w docelowym języku
		 * @param input ciąg wejściowy
		 * @param languageType typ języka, do którego mają być skonwertowane cyfry
		 * @return ciąg po konwersji 
		 */
		public static function convertDigitsToLanguage(input:String, languageType:String):String {
			var convArray:Array;
			// wybór tablicy konwersji (w zależności od rodzaju języka docelowego)
			switch (languageType) {
				case TextUtil.LANGUAGE_TYPE_ARABIC:
					convArray = DIGITS_TYPE_ARABIC;
				break;
				default:
					return input;
			}
			// konwersja
			var digits:Array = input.match(/\d/g);
			for each (var digit:String in digits) {
				input = input.replace(digit, convArray[digit]);
			}
			return input;
		}
		
		/**
		 * Usuwa wszystkie znaki końca wiersza z podanego tekstu.
		 * @param text
		 * @return przerobiony tekst
		 */
		public static function removeEndLines( text:String ):String {
			var endLineRegExp:RegExp = /[\t\n\r]+/g;
			text = text.replace( endLineRegExp, "" );			
			return text;
		}
		
		
		/**
		 * Ocenia długość słowa na podstawie należących do niego liter
		 * @param word oceniany string
		 * @return oszacowana szerokość słowa (waga)
		 */
		public static function getStringWidth (	word:String ):uint {
			word = word.toLowerCase();
			var wordWidth:Number = WIDTH_BASE[word];
			if ( !isNaN(wordWidth) )
				return wordWidth;
			wordWidth = 0;
			
			for (var i:Number=0;i<word.length;i++) {
				var c:String = word.charAt( i );
				if (iChars.indexOf(c)!=-1)
					wordWidth += iWidth;
				else if (fChars.indexOf(c)!=-1)
				   wordWidth += fWidth;
				else if (mChars.indexOf(c)!=-1)
					wordWidth += mWidth;
				else
				   wordWidth += charWidth;
			}
			WIDTH_BASE[word] = wordWidth;
			return wordWidth;
		}
		
		/**
		 * Zwraca najprawdopodniejsze najszersze słowo z podanych.
		 * @param text tekst zawierający oceniane słowa
		 * @return wybrane najszersze słowo z tekstu
		 */
		public static function getWidestWordFromString( text:String ):String {
			return getWidestWord( text.split(/\s/) );
		}
		
		/**
		 * Zwraca najprawdopodniejsze najszersze słowo z podanych.
		 * @param words tablica słow - zostanie posortowana w/g szerokości
		 * @return wybrane najszersze słowo z tablicy
		 */
		public static function getWidestWord( words:Array ):String {
			if (!words.length)
				return null;
			words.sort( TextUtil.textLengthComparator );
			return words[0];
		}
		
		private static function textLengthComparator(a:Object,b:Object):Number {
			var al:Number = getStringWidth( String(a) );
			var bl:Number = getStringWidth( String(b) );
			if (al==bl)
				return 0;
			return (al>bl)? -1 : 1;
		}
	}
}